package ticketingsystem;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
public class TicketingDS implements TicketingSystem {
    private Train[] train;
    private AtomicInteger tid;
    private ConcurrentHashMap<Long, Ticket> sold;

    public TicketingDS(int routenum, int coachnum, int seatnum, int stationnum, int threadnum){
        tid = new AtomicInteger(1);

        train = new Train[routenum];

        for(int i = 0; i < routenum; i++){
            train[i] = new Train(coachnum, seatnum, stationnum);
        }
        sold = new ConcurrentHashMap<Long, Ticket>();
    }
    public TicketingDS(){
        tid = new AtomicInteger(1);

        train = new Train[5];

        for(int i = 0; i < 5; i++){
            train[i] = new Train(8, 100, 10);
        }
        sold = new ConcurrentHashMap<Long, Ticket>();
    }
    @Override
    public Ticket buyTicket(String passenger, int route, int departure, int arrival) {
        int[] sid = train[route - 1].buy(departure - 1, arrival - 1);
        if(sid !=null) {
            Ticket ticket = new Ticket();
            ticket.tid = tid.getAndIncrement();
            ticket.passenger = passenger;
            ticket.route = route;
            ticket.departure = departure;
            ticket.arrival = arrival;
            ticket.coach = sid[0];
            ticket.seat = sid[1];
            sold.put(ticket.tid, ticket);
            return ticket;
        }
        return null;
    }
    @Override
    public int inquiry(int route, int departure, int arrival) {
        return train[route - 1].query(departure - 1, arrival - 1);
    }

    @Override
    public boolean refundTicket(Ticket ticket) {
        if(!sold.containsKey(ticket.tid) || !ticket.equals(sold.get(ticket.tid))){
            return false;
        }

        if(train[ticket.route - 1].refund(ticket.coach,ticket.seat, ticket.departure - 1, ticket.arrival - 1)){
            return sold.remove(ticket.tid, ticket);
        }
        return false;
    }
}
